import pinia from './store'
import useUserStore from '@/store/modules/user'
import setting from '@/setting'
//进度条插件
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })

// 用于配置用户路由鉴权
import router from '@/router'
const userStore = useUserStore(pinia)

router.beforeEach(async (to: any, from: any, next: any) => {
  nprogress.start()
  const token = userStore.token
  if (token) {
    document.title = `${setting.name} - ${to.meta.title}`
    // 有token
    if (to.path === '/login') return next({ path: '/' })
    if (userStore.username) return next()
    try {
      await userStore.getUerInfo()
      next({ ...to })
    } catch (error) {
      // 用户token过期
      await userStore.userLogout()
      next({ path: '/login', query: { redirect: to.path } })
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

// 全局后置守卫
router.afterEach((to: any, from: any, next: any) => {
  nprogress.done()
})
// 路由简介
//  一级路由
// login
// 404
// screen
// 首页
// 任意路由
// 权限管理 : 三个子路由
// 商品管理 : 四个子路由
// 全局前置守卫
